package com.imooc.spring.jdbc.service;

import com.imooc.spring.jdbc.dao.EmployeeDao;
import com.imooc.spring.jdbc.entity.Employee;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.Date;

public class EmployeeService {
    private EmployeeDao employeeDao;
    private DataSourceTransactionManager transactionManager;


    // 批量导入输入
    public void batchImport() {
        // 定义了事务默认的标准配置
        TransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
        // 开始一个事务
        TransactionStatus status = transactionManager.getTransaction(transactionDefinition);
        try {
            for (int i = 1; i < 10; i++) {
//                if (i == 3) {
//                    throw new RuntimeException("意料之外的异常");
//                }
                Employee employee = new Employee();
                employee.setEno(8000 + i);
                employee.setEname("员工" + i);
                employee.setSalary(4000f);
                employee.setDname("运营部");
                employee.setHiredate(new Date());
                employeeDao.insertEmployee(employee);
            }
            // 提交事务
            transactionManager.commit(status);
        } catch (RuntimeException e) {
            // 回滚事务
            transactionManager.rollback(status);
            throw e;
        }

    }

    public EmployeeDao getEmployeeDao() {
        return employeeDao;
    }

    public void setEmployeeDao(EmployeeDao employeeDao) {
        this.employeeDao = employeeDao;
    }

    public DataSourceTransactionManager getTransactionManager() {
        return transactionManager;
    }

    public void setTransactionManager(DataSourceTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }
}
